package com.example.imitationqqsound.qqsound;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.imitationqqsound.R;
import com.example.imitationqqsound.utils.AudioRecordManager;

import org.fmod.FMOD;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ChatActivity extends AppCompatActivity implements View.OnClickListener {

    private LinearLayout ll_bottom_btn;
    private LinearLayout ll_record;
    private ImageView iv_sound;
    private ImageView iv_record;
    private Chronometer chro_record_tip;
    private LinearLayout ll_change;
    private ImageView iv_change_normal, iv_change_luoli, iv_change_uncle, iv_change_thrillers, iv_Change_funny, iv_change_ethereal;
    private TextView tv_cancel;
    private TextView tv_send;
    private Timer timer;

    private String TAG = "MainActivity";
    private AudioRecordManager mManager;
    private boolean isSend = false;

    private static final int MODE_NORMAL = 0;//正常
    private static final int MODE_LUOLI = 1;//萝莉
    private static final int MODE_DASHU = 2;//大叔
    private static final int MODE_JINGSONG = 3;//惊悚
    private static final int MODE_GAOGUAI = 4;//搞怪
    private static final int MODE_KONGLING = 5;//空灵

    private String path = "sdcard/storage/emulated/0/DCIM/arm/211217_115135.wav";

    private native void voiceChangeNative(int modeNormal, String path);

    private void playEnd(String msg) {
        Toast.makeText(this, msg + "", Toast.LENGTH_SHORT).show();
    }

    private native void playInterrupt();

    static {
        System.loadLibrary("native-lib");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);

        initView();
        initEvent();

    }

    private void initEvent() {
        FMOD.init(this);
        AudioRecordManager.init();//初始化目录
        //初始化
        mManager = AudioRecordManager.NewInstance();
        checkPermission();
    }

    //申请权限列表
    private int REQUEST_CODE = 1001;
    private String[] permissions = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.RECORD_AUDIO
    };
    //拒绝权限列表
    private List<String> refusePermissions = new ArrayList<>();

    /**
     * 6.0以上要动态申请权限
     */
    private void checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            for (int i = 0; i < permissions.length; i++) {
                if (ContextCompat.checkSelfPermission(this,
                        permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                    refusePermissions.add(permissions[i]);
                }
            }
            if (!refusePermissions.isEmpty()) {
                String[] permissions = refusePermissions.toArray(new String[refusePermissions.size()]);
                ActivityCompat.requestPermissions(this, permissions, REQUEST_CODE);
            }
        }

    }

    /**
     * 权限结果回调
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults != null) {
                for (int i = 0; i < permissions.length; i++) {
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        Log.d(TAG, permissions[i] + "   被禁用");
                    }
                }
            }
        }
    }


    private void initView() {
        ll_bottom_btn = findViewById(R.id.ll_bottom_btn);
        ll_record = findViewById(R.id.ll_record);
        iv_sound = findViewById(R.id.iv_sound);
        iv_record = findViewById(R.id.iv_record);
        chro_record_tip = findViewById(R.id.chro_record_tip);
        ll_change = findViewById(R.id.ll_change);
        iv_change_normal = findViewById(R.id.iv_change_normal);
        iv_change_luoli = findViewById(R.id.iv_change_luoli);
        iv_change_uncle = findViewById(R.id.iv_change_uncle);
        iv_change_thrillers = findViewById(R.id.iv_change_thrillers);
        iv_Change_funny = findViewById(R.id.iv_Change_funny);
        iv_change_ethereal = findViewById(R.id.iv_change_ethereal);
        tv_cancel = findViewById(R.id.tv_cancel);
        tv_send = findViewById(R.id.tv_send);

        iv_sound.setOnClickListener(this);
        iv_change_normal.setOnClickListener(this);
        iv_change_luoli.setOnClickListener(this);
        iv_change_uncle.setOnClickListener(this);
        iv_change_thrillers.setOnClickListener(this);
        iv_Change_funny.setOnClickListener(this);
        iv_change_ethereal.setOnClickListener(this);
        tv_cancel.setOnClickListener(this);

        timer = new Timer();
        chro_record_tip.setBase(SystemClock.elapsedRealtime());//计时器清零
        iv_record.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        isSend = false;
                        chro_record_tip.setBase(SystemClock.elapsedRealtime());//计时器清零
                        chro_record_tip.start();
                        //录音
                        mManager.startRecord();
                        break;
                    case MotionEvent.ACTION_UP:
                        chro_record_tip.stop();
                        //停止
                        mManager.stopRecord();
                        ll_record.setVisibility(View.GONE);
                        ll_change.setVisibility(View.VISIBLE);
                        ll_bottom_btn.setVisibility(View.VISIBLE);
                        mManager.pcmToWav(mManager.getPcmFile().getPath(), mManager.getWavFile().getPath());
                        break;
                }
                return true;
            }
        });

        tv_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isSend = true;
                ll_record.setVisibility(View.GONE);
                ll_change.setVisibility(View.VISIBLE);
                ll_bottom_btn.setVisibility(View.VISIBLE);
            }
        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_sound:
                ivSoundClick();
                break;
            case R.id.iv_change_normal://原声
                changeVoice(MODE_NORMAL);
//                path = mManager.getWavFile().getPath() == null?"":mManager.getWavFile().getPath();
//                Log.e(TAG,"wavfile:"+path);
//                voiceChangeNative(MODE_NORMAL, path);
                break;
            case R.id.iv_change_luoli://萝莉
                changeVoice(MODE_LUOLI);
//                path = mManager.getWavFile().getPath() == null?"":mManager.getWavFile().getPath();
//                voiceChangeNative(MODE_LUOLI, path);
                break;
            case R.id.iv_change_uncle://大叔
                changeVoice(MODE_DASHU);
//                path = mManager.getWavFile().getPath() == null?"":mManager.getWavFile().getPath();
//                voiceChangeNative(MODE_DASHU, path);
                break;
            case R.id.iv_change_thrillers://惊悚
                changeVoice(MODE_JINGSONG);
//                path = mManager.getWavFile().getPath() == null ? "" : mManager.getWavFile().getPath();
//                voiceChangeNative(MODE_JINGSONG, path);
                break;
            case R.id.iv_Change_funny://搞怪
                changeVoice(MODE_GAOGUAI);
//                path = mManager.getWavFile().getPath() == null ? "" : mManager.getWavFile().getPath();
//                voiceChangeNative(MODE_GAOGUAI, path);
                break;
            case R.id.iv_change_ethereal://空灵
                changeVoice(MODE_KONGLING);
//                path = mManager.getWavFile().getPath() == null ? "" : mManager.getWavFile().getPath();
//                voiceChangeNative(MODE_KONGLING, path);
                break;
            case R.id.tv_cancel://取消
                chro_record_tip.setBase(SystemClock.elapsedRealtime());//计时器清零
                ll_record.setVisibility(View.VISIBLE);
                ll_change.setVisibility(View.GONE);
                ll_bottom_btn.setVisibility(View.GONE);
                break;
        }
    }

    private void ivSoundClick() {
        isSend = false;
        if (iv_sound.isSelected()) {
            iv_sound.setSelected(false);
            ll_record.setVisibility(View.GONE);
        } else {
            iv_sound.setSelected(true);
            ll_record.setVisibility(View.VISIBLE);
        }
    }

    private ExecutorService executor;
    private void changeVoice(int mode) {

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                if (!isSend){
                    path = mManager.getWavFile().getPath() == null?"":mManager.getWavFile().getPath();
                }else{
                    path = "sdcard/storage/emulated/0/DCIM/arm/211217_115135.wav";
                }
                voiceChangeNative(mode, path);
            }
        };

        executor = Executors.newSingleThreadExecutor();
        executor.execute(runnable);



//
//        path = mManager.getWavFile().getPath() == null?"":mManager.getWavFile().getPath();
//        voiceChangeNative(mode, path);

//        if (handlerThread == null){
//            handlerThread = new HandlerThread("voice");
//            handlerThread.start();
//            handler = new Handler(handlerThread.getLooper()) {
//                @Override
//                public void handleMessage(@NonNull Message msg) {
////                super.handleMessage(msg);
//                    path = mManager.getWavFile().getPath() == null ? "" : mManager.getWavFile().getPath();
//                    voiceChangeNative(mode, path);
//                }
//            };
//        }

    }

    @Override
    protected void onDestroy() {
        executor.shutdownNow();
        super.onDestroy();
    }
}